package com.bigtotoro.shuiyincamera.image;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.editimage.Constacts;
import com.bigtotoro.shuiyincamera.model.RatioItem;
import com.bigtotoro.shuiyincamera.editimage.utils.BitmapUtils;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.editimage.utils.Matrix3;
import com.bigtotoro.shuiyincamera.editimage.view.CropImageView;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouch;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouchBase;
import com.bigtotoro.shuiyincamera.util.FileUtils;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片剪裁
 */
public class Cut02Activity extends BaseActivity implements View.OnClickListener {
    public static final int REQUEST_PERMISSON_SORAGE = 1;
    public static final int ACTION_REQUEST_EDITIMAGE = 9;
    private Cut02Activity context;
    private int imageWidth, imageHeight;//

    private Bitmap mainBitmap;  //操作完成后获得的图片
    public ImageViewTouch mainImage; // 底部图层，放原始照片这一层
    private View backBtn;

    private LinearLayout ratioList;
    private static List<RatioItem> dataList = new ArrayList<RatioItem>();
    static {
        // init data
        dataList.add(new RatioItem("默认", -1f));
        dataList.add(new RatioItem("1:1", 1f));
        dataList.add(new RatioItem("1:2", 1 / 2f));
        dataList.add(new RatioItem("1:3", 1 / 3f));
        dataList.add(new RatioItem("2:3", 2 / 3f));
        dataList.add(new RatioItem("3:4", 3 / 4f));
        dataList.add(new RatioItem("2:1", 2f));
        dataList.add(new RatioItem("3:1", 3f));
        dataList.add(new RatioItem("3:2", 3 / 2f));
        dataList.add(new RatioItem("4:3", 4 / 3f));
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkInitImageLoader();//检测图片载入框架是否初始化
        setContentView(R.layout.activity_cut02);

        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels;
        imageHeight = metrics.heightPixels;

        initBase();
        initView();
        getData();
    }
    public static String filePath;// 需要编辑图片路径
    public String saveFilePath;// 生成的新图片路径
    private void getData() {
        context = this;
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels;
        imageHeight = metrics.heightPixels;

        filePath = getIntent().getStringExtra("path"); //图片原始路径
        File outputFile = FileUtils.genEditFile();  //保存路径
        saveFilePath = outputFile.getAbsolutePath();
        loadImage(filePath);
    }

    public TextView selctedTextView,btn_submit;
    public CropImageView mCropPanel;// 剪裁画布
    private void initView() {
        ratioList = findViewById(R.id.ratio_list_group);//1:2,1:3的菜单
        setUpRatioList(); //为比例菜单添加点击事件

        btn_submit = findViewById(R.id.btn_submit);
        btn_submit.setOnClickListener(this);

        mCropPanel =  findViewById(R.id.crop_panel); //添加图片表情的画布
        mCropPanel.setVisibility(View.VISIBLE);
        mainImage = findViewById(R.id.main_image);// 页面正中的图片显示控件

        backBtn = findViewById(R.id.back_btn);// 左上角退出按钮
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


    }
    private CropRationClick mCropRationClick = new CropRationClick();
    public static int SELECTED_COLOR = Color.YELLOW;
    public static int UNSELECTED_COLOR = Color.BLACK;
    private List<TextView> textViewList = new ArrayList<TextView>();
    private void setUpRatioList() {
        ratioList.removeAllViews();
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER_VERTICAL;
        params.leftMargin = 20;
        params.rightMargin = 20;
        for (int i = 0, len = dataList.size(); i < len; i++) {
            TextView text = new TextView(this);
            text.setTextColor(getResources().getColor(R.color.font_6));
            text.setTextSize(20);
            text.setText(dataList.get(i).getText());
            textViewList.add(text);
            ratioList.addView(text, params);
            text.setTag(i);
            if (i == 0) {
                selctedTextView = text;
            }
            dataList.get(i).setIndex(i);
            text.setTag(dataList.get(i));
            text.setOnClickListener(mCropRationClick);
        }// end for i
        selctedTextView.setTextColor(getResources().getColor(R.color.theme_color));
    }

    /**
     * 选择剪裁比率
     */
    private final class CropRationClick implements View.OnClickListener {  //剪裁比例点击监听事件
        @Override
        public void onClick(View v) {
            //如果剪裁区域不显示，让其显示

            if (mCropPanel.getVisibility()==View.GONE){
                mCropPanel.setVisibility(View.VISIBLE);
                mainImage.setImageBitmap(mainBitmap);
                mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
                mainImage.setScaleEnabled(false);// 禁用缩放
            }

            TextView curTextView = (TextView) v;
            selctedTextView.setTextColor(getResources().getColor(R.color.font_6));

            RatioItem dataItem = (RatioItem) v.getTag();

            selctedTextView = curTextView;
            selctedTextView.setTextColor(getResources().getColor(R.color.theme_color));

            //设置剪裁区域比例
            RectF rectF = mainImage.getBitmapRect(); //获取默认比例,根据原图比例设置

            //调整剪裁比例
            mCropPanel.setRatioCropRect(rectF,
                    dataItem.getRatio());//背景图片尺寸，剪裁比例(1/2,1/3，默认是-1)
        }
    }

    private LoadImageTask mLoadImageTask;
    public void loadImage(String filepath) {
        if (mLoadImageTask != null) {
            mLoadImageTask.cancel(true);
        }
        mLoadImageTask = new LoadImageTask();
        mLoadImageTask.execute(filepath);
    }

    /**
     * 这个方法是为了获取图片的，异步获取图片方法
     */
    private final class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {
            return BitmapUtils.getSampledBitmap(params[0],
                    imageWidth / 4, imageHeight / 4);
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(Bitmap result) {
            super.onCancelled(result);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            changeMainBitmap(result, false);
            mainImage.setScaleEnabled(false);// 禁用缩放

            // 设置完与屏幕匹配的尺寸  确保变换矩阵设置生效后才设置裁剪区域
            mainImage.postDelayed(new Runnable() {
                @Override
                public void run() {
                    final RectF r = mainImage.getBitmapRect();
                    mCropPanel.setCropRect(r);
                }
            },200);//在原版的基础上加了200延迟，不加延迟可能拿不到getBitmapRect
        }

    }
    /**
     * @param newBit
     * @param needPushUndoStack
     */
    public void changeMainBitmap(Bitmap newBit, boolean needPushUndoStack) { //第二个参数是是否将图片压栈
        if (newBit == null)  //如果获取到的图片为空，返回
            return;
        if (mainBitmap == null || mainBitmap != newBit) {  //如果获取到的图片为空，返回
            mainBitmap = newBit;
            mainImage.setImageBitmap(mainBitmap);
            mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        }
    }

    /**
     * 保存剪切图片
     */
    public void applyCropImage() {
        // System.out.println("保存剪切图片");
        CropImageTask task = new CropImageTask();
        task.execute(mainBitmap);
    }

    /**
     * 图片剪裁，生成剪裁后的图片 异步任务
     *
     */
    private final class CropImageTask extends AsyncTask<Bitmap, Void, Bitmap> {
        private Dialog dialog;

        @Override
        protected void onCancelled() {
            super.onCancelled();
            dialog.dismiss();
        }

        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(Bitmap result) {
            super.onCancelled(result);
            dialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = BaseActivity.getLoadingDialog(Cut02Activity.this, R.string.saving_image,
                    false);
            dialog.show();
        }

        @SuppressWarnings("WrongThread")
        @Override
        protected Bitmap doInBackground(Bitmap... params) {
            /**
             * 剪裁区域的区域mCropPanel.getCropRect()
             * **/
            RectF cropRect = mCropPanel.getCropRect();// 剪切区域矩形
            Matrix touchMatrix = mainImage.getImageViewMatrix();
            // Canvas canvas = new Canvas(resultBit);
            float[] data = new float[9];
            touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
            Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
            Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
            Matrix m = new Matrix();
            m.setValues(inverseMatrix.getValues());
            m.mapRect(cropRect);// 变化剪切矩形

            Bitmap resultBit = Bitmap.createBitmap(params[0],
                    (int) cropRect.left, (int) cropRect.top,
                    (int) cropRect.width(), (int) cropRect.height());

            return resultBit;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            super.onPostExecute(result);
            dialog.dismiss();
            if (result == null)
                return;
            changeMainBitmap(result,true);//使用剪裁后的图片替换mainImage初始 背景图
            mCropPanel.setCropRect(mainImage.getBitmapRect());
            backToMain();
            //保存到litepal

            doSaveImage();

        }
    }

    private  SaveImageTask mSaveImageTask;
    protected void doSaveImage() {
        if (mSaveImageTask != null) {
            mSaveImageTask.cancel(true);
        }
        //在这里保存bitmap_list里的内容，取后一半的数据
        mSaveImageTask = new SaveImageTask();
        mSaveImageTask.execute(mainBitmap); //保存的是mainBitmap

    }

    private final class SaveImageTask extends AsyncTask<Bitmap, Void, Boolean> {
        private Dialog dialog;
        @Override
        protected Boolean doInBackground(Bitmap... params) {
            if (TextUtils.isEmpty(saveFilePath))  //saveFilePath通过EditImageActivity.start方法中传入的
                return false;
            return BitmapUtils.saveBitmap(params[0], saveFilePath);
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
            dialog.dismiss();
        }
        @Override
        protected void onCancelled(Boolean result) {
            super.onCancelled(result);
            dialog.dismiss();
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = getLoadingDialog(Cut02Activity.this,R.string.saving_image, false);
            dialog.show();
        }
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            dialog.dismiss();
            if (result) {
                //放入图片列表
                MyArt art = new MyArt();
                art.setHeight(imageHeight);
                art.setWidth(imageWidth);
                Long millis = System.currentTimeMillis();
                art.setCreate_time(millis+"");
                art.setPath(saveFilePath);
                art.setType(0);
                art.save();
                Toast.makeText(context, "图片保存在" + saveFilePath.toString(),
                        Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(Cut02Activity.this, ShowMyArtsActivity.class);
                intent.putExtra("create_time", art.getTrueCreateTime());
                intent.putExtra(Constacts.EXTRA_OUTPUT, saveFilePath);
                intent.putExtra("width", imageHeight);
                intent.putExtra("height", imageWidth);
                intent.putExtra("type", "0");

                FileUtil.ablumUpdate(Cut02Activity.this, saveFilePath,0);//更新相册
                startActivity(intent);
                finish();
            } else {
                Toast.makeText(Cut02Activity.this, R.string.save_error, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void backToMain() {
            //如果是从主菜单点击进入的裁剪菜单，需要执行backtomain，如果是直接进入的裁剪功能模块，应该直接退出
            mCropPanel.setVisibility(View.GONE);//隐藏剪裁画布
            mainImage.setScaleEnabled(true);// 恢复缩放功能
            if (selctedTextView != null) {
                selctedTextView.setTextColor(UNSELECTED_COLOR);
            }
            mCropPanel.setRatioCropRect(mainImage.getBitmapRect(), -1);//重置剪裁面，就是剪裁区域截取
    }

    private int mode = 0;//0应用1保存
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                    applyCropImage();


                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("Cut02Activity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("Cut02Activity");//统计页面
        MobclickAgent.onPause(this);
    }

}